#include "keyled.h"

KEYS ScanPressedKey(uint32_t timeout){
	KEYS key = KEY_NONE;
	uint32_t tickstart = HAL_GetTick();

	const uint32_t btnDelay = 20;
	GPIO_PinState keyState;
	while(1){

		keyState = HAL_GPIO_ReadPin(KeyLeft_GPIO_Port,KeyLeft_Pin);
		if(keyState == GPIO_PIN_RESET){
			HAL_Delay(btnDelay); //延时跳过前抖动期
			keyState = HAL_GPIO_ReadPin(KeyLeft_GPIO_Port,KeyLeft_Pin); //再采样
			if(keyState == GPIO_PIN_RESET)
				return KEY_LEFT;
		}
		keyState = HAL_GPIO_ReadPin(KeyRight_GPIO_Port,KeyRight_Pin);
		if(keyState == GPIO_PIN_RESET){
			HAL_Delay(btnDelay); //延时跳过前抖动期
			keyState = HAL_GPIO_ReadPin(KeyRight_GPIO_Port,KeyRight_Pin); //再采样
			if(keyState == GPIO_PIN_RESET)
				return KEY_RIGHT;
		}

		keyState = HAL_GPIO_ReadPin(KeyDown_GPIO_Port,KeyDown_Pin);
		if(keyState == GPIO_PIN_RESET){
			HAL_Delay(btnDelay); //延时跳过前抖动期
			keyState = HAL_GPIO_ReadPin(KeyDown_GPIO_Port,KeyDown_Pin); //再采样
			if(keyState == GPIO_PIN_RESET)
				return KEY_DOWN;
		}
		keyState = HAL_GPIO_ReadPin(KeyUp_GPIO_Port,KeyUp_Pin);
		if(keyState == GPIO_PIN_SET){
			HAL_Delay(btnDelay); //延时跳过前抖动期
			keyState = HAL_GPIO_ReadPin(KeyUp_GPIO_Port,KeyUp_Pin);
			if(keyState == GPIO_PIN_SET)
				return KEY_UP;
		}
		if(timeout != KEY_WAIT_ALWAYS) { //没有按键按下会计算超时，timeout时退出
			if((HAL_GetTick() - tickstart) > timeout)
				break;

		}

	}
	return key;
}
